package com.borrowed.book.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.borrowed.book.system.domain.WxLoginOutDto;
import com.borrowed.book.system.service.SystemLoginService;
import com.borrowed.book.system.util.HttpUtil;
import com.borrowed.book.user.domain.SUser;
import org.apache.shiro.SecurityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Service;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

@Service
public class SystemLoginServiceImpl implements SystemLoginService {
    @Override
    public WxLoginOutDto getWxLoginInfo(String code,String appId,String appSecret) throws Exception {
        String result="";
        try{//请求微信服务器，用code换取openid。HttpUtil是工具类
            String url="https://api.weixin.qq.com/sns/jscode2session?appid="
                    + appId + "&secret="
                    + appSecret + "&js_code="
                    + code
                    + "&grant_type=authorization_code";
            result = HttpUtil.doGet(url, null);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObj = JSONObject.parseObject(result);//解析从微信服务器上获取到的json字符串;
        WxLoginOutDto wxOutDto=null;
        String openId="";
        String sessionKey="";
        if(jsonObj.get("openid")!=null){
            openId=jsonObj.get("openid").toString();
            sessionKey=jsonObj.getString("session_key").toString();
            wxOutDto=new WxLoginOutDto();
            wxOutDto.setOpenId(openId);
            wxOutDto.setSessionKey(sessionKey);
        }else{
            throw  new Exception(jsonObj.toJSONString());
        }
        return wxOutDto;
    }

    /**
     * 解析微信手机号码
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param iv 加密算法的初始向量
     * @return
     * @throws Exception
     */
    @Override
    public String getPhoneNumber(String encryptedData,String iv) throws Exception {
        String phoneNumber=null;
        JSONObject obj=null;

        SUser sysUser = (SUser)SecurityUtils.getSubject().getPrincipal();
        String session_key=sysUser.getSessionKey();
        encryptedData=encryptedData.replaceAll(" ","+");
        byte[] dataByte = Base64.decodeBase64(encryptedData);
        byte[] keyByte = Base64.decodeBase64(session_key);
        byte[] ivByte = Base64.decodeBase64(iv);
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                obj=JSONObject.parseObject(result);
            }
            System.out.println(obj);
            if(obj!=null) {
                phoneNumber = obj.get("phoneNumber").toString();
            }
            return phoneNumber;
    }

}
